package com.rk.cmn.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rk.cmn.mapper.DictMapper;
import com.rk.cmn.service.DictService;
import com.rk.hosp.model.cmn.Dict;
import com.rk.hosp.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :Rk.
 * @date : 2022/11/3
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;


    //这个注解表示第一次来查询的时候是查数据库，第二次开始就从缓存中获取
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChlidData(Long id) {
        LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dict::getParentId,id);
        //查出数据的子节点
        List<Dict> list = baseMapper.selectList(lqw);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : list) {
            Long did = dict.getId();
            boolean hasChildren = isChildren(did);
            dict.setHasChildren(hasChildren);
        }
        return list;
    }

    //判断该节点下是否有子节点
    private boolean isChildren(Long id) {
        Integer num = baseMapper.countChildren(id);
        if(num>0){
            return true;
        }
        return false;
    }

    /**
     * excel导出
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查询所有需要导出的数据
            List<Dict> dictList = dictMapper.selectList(null);
            //vo
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            //将dict复制到dictVo
            for(Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
                dictVoList.add(dictVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 模板下载
     * @param response
     */
    @Override
    public void downModel(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<DictEeVo> dictVoList=new ArrayList<>();
        dictVoList.add(new DictEeVo(5000L,4000L,"猫","10","sn010"));
        dictVoList.add(new DictEeVo(5001L,4000L,"狗","11","sn011"));
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
    }


    /**
     * 根据上级编码与值获取数据字典名称
     * @param dictCode
     * @param value
     * @return
     * Cacheable这个注解表示第一次来查询的时候是查数据库，第二次开始就从缓存中获取
     * @Cacheable注解第一个参数为redis中key的兼职
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, String value) {
        LambdaQueryWrapper<Dict> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Dict::getValue,value);
        //如果上级编码为空
        if (StringUtils.isEmpty(dictCode))
        {
            //where value=#{value}
            Dict dict = dictMapper.selectOne(lqw);
            if(dict!=null){
                return dict.getName();
            }
        }else {
            //如果上级编码不为空 就查询该级的parent_id  然后通过Parent_id和value来找到dict
            //根据dictCode查询dict对象
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parentId = codeDict.getId();
            lqw.eq(Dict::getParentId,parentId);
            Dict dict = dictMapper.selectOne(lqw);
            if(dict!=null){
                return dict.getName();
            }
        }
        return "";
    }

    /**
     * 通过dictCode去查询Dict
     * @param dictCode
     * @return
     */
    public Dict getDictByDictCode(String dictCode){

        LambdaQueryWrapper<Dict> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Dict::getDictCode,dictCode);
        Dict dict = dictMapper.selectOne(lqw);
        return dict;
    }


    /**
     * 通过dictCode去查询字典数据
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        if(dict==null){
            return null;
        }
        Long id = dict.getId();
        LambdaQueryWrapper<Dict> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Dict::getParentId,id);
        List<Dict> list = dictMapper.selectList(lqw);
        return list;
    }


}
